<?php

namespace App\Trip\Geo\Amap;

use Exception;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\Cache;


/**
 *
 */
class District extends Amap
{
    /**
     * 规则：设置显示下级行政区级数（行政区级别包括：国家、省/直辖市、市、区/县4个级别）
     *
     * 可选值：0、1、2、3
     *
     * 0：不返回下级行政区；
     *
     * 1：返回下一级行政区；
     *
     * 2：返回下两级行政区；
     *
     * 3：返回下三级行政区；
     */
    const SUBDISTRICTS
        = [
            0, 1, 2, 3,
        ];


    /**
     *
     * @throws GuzzleException
     * @throws Exception
     */
    public function districts(string $keywords = '100000', int $subdistrict = 0, ?int $offset = 20, ?int $page = 1): array
    {
        if ($keywords != '100000') {
            // 此时注意分页问题
        }

        if (!in_array($subdistrict, self::SUBDISTRICTS)) {
            throw new Exception("参数错误");
        }

        $url = $this->buildQuery("/v3/config/district", [
            "keywords"    => $keywords,
            "subdistrict" => $subdistrict,
        ]);

        $cache_key = "District:query:{$keywords}_{$subdistrict}";
        if (Cache::has($cache_key)) {
            $districts = json_decode(Cache::get($cache_key), true);
        } else {
            $resp    = $this->client->get($url);
            $content = json_decode($resp->getBody()->getContents(), true);
            if (!isset($content['districts'])) {
                throw new Exception($content['msg'] ?? '查询失败');
            }

            $districts = $content['districts'];
            Cache::put($cache_key, collect($districts)->toJson(), config('trip.ttl.day'));
        }
        return $districts;
    }
}